package daily_task

import (
	"go_server/game_server/constants"
	"go_server/game_server/dao/daily_dao"
	"go_server/game_server/dataconfig/config_manager"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
	"gorm.io/datatypes"
	"time"
)

// S2C_UpdateDailyTask 处理每日任务事件更新，根据事件类型和事件内容更新玩家的每日任务进度或状态
// 参数:
// conn - 连接对象，用于发送消息给客户端
// roleId - 玩家ID
// taskType - 任务类型
// taskEvent - 任务事件
// parms - 任务参数，包括任务ID和达成的数值
// 返回值:
// int32 - 返回错误码，0表示成功
func (s *DailyTaskService) S2C_UpdateDailyTask(conn ziface.IConnection, roleId int64, taskType int32, taskEvent int32, parms map[string]int32) pb.ErrorCodeManager {
	zlog.Infof("每日任务事件接收处理,taskType=%d,taskEvent=%d,parms=%v", taskType, taskEvent, parms)

	id := parms["id"]     // 例如：建筑id或者关卡id,可传0
	num := parms["value"] // 达成的数值

	// 根据事件类型和事件内容获取相关的任务配置列表
	baseTaskList := config_manager.GetStcTableTask_SheetTaskListByEvent(taskType, taskEvent)
	if len(baseTaskList) == 0 {
		zlog.Errorf("baseTaskList 事件对应任务配置不存在,taskType=%d,taskEvent=%d", taskType, taskEvent)
		return pb.ErrorCodeManager_DAILY_TASK_UNFIND
	}

	// 获取当前每日任务进度
	dateKey := time.Now().Format("20060102")
	fields := []string{"daily_task"}
	row := daily_dao.GetDailyByDateKey(dateKey, roleId, fields)

	taskIdToProgress := make(map[int32][]int32)

	if row != nil && row.DailyTask.Data() != nil {
		taskIdToProgress = row.DailyTask.Data()
	}

	eventSet := util.NewSet[int32]()
	eventSet.AddValue(constants.FixedValueEvents)

	var isFixedValue bool // 是否是固定值判断
	if eventSet.Contains(taskEvent) {
		isFixedValue = true
	} else {
		isFixedValue = false
	}

	// 标记是否有任务进度或状态更新
	hasUpdate := false

	// 遍历任务列表，更新任务进度或状态
	for taskId, taskVal := range baseTaskList {
		if len(taskVal.Value) <= 0 {
			continue
		}

		var requiredLimit int32

		if len(taskVal.Value) >= 2 {
			requiredId := taskVal.Value[0]
			requiredLimit = taskVal.Value[1]
			if requiredId != id {
				continue
			}
		} else {
			requiredLimit = taskVal.Value[0]
		}

		taskProgress, exists := taskIdToProgress[taskId]
		if exists {
			if taskProgress[2] >= 1 {
				continue
			}

			var newProgress int32
			if isFixedValue { // 如果是固定值判断
				newProgress = num // 最新等级、星级
			} else {
				newProgress = taskProgress[1] + num // 最新进度
			}

			if newProgress >= requiredLimit {
				newProgress = requiredLimit
				taskIdToProgress[taskId][1] = newProgress
				taskIdToProgress[taskId][2] = 1
			} else {
				if isFixedValue { // 如果是固定值判断
					if newProgress > taskProgress[1] {
						taskIdToProgress[taskId][1] = newProgress // 更新进度
					}
				} else {
					taskIdToProgress[taskId][1] = newProgress // 更新进度
				}
			}
		} else {
			if num >= requiredLimit {
				taskIdToProgress[taskId] = []int32{taskId, requiredLimit, 1}
			} else {
				taskIdToProgress[taskId] = []int32{taskId, num, 0}
			}
		}

		hasUpdate = true
	}

	// 如果有任务进度或状态更新，则更新数据库并推送更新消息给客户端
	if hasUpdate {
		dailyObj := daily_dao.Daily{
			DateKey:   dateKey,
			RoleId:    roleId,
			DailyTask: datatypes.NewJSONType(taskIdToProgress),
		}

		daily_dao.UpdateDailyByDateKey(&dailyObj, fields)

		msgS2C := ServiceObj.GetDailyTaskList.GetDailyTaskListApiS2C(roleId)
		conn.SendBuffPBMsg(uint32(pb.ProtocolManager_GetDailyTaskList), msgS2C)
	}

	return pb.ErrorCodeManager_SUCCESS
}
